// This file is part of Module Proxy.

// Module Proxy is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Module Proxy is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Module Proxy.  If not, see <https://www.gnu.org/licenses/>.


//         Copyright (C) 2021 - 2030  关中麦客  
//         All rights reserved
//
//         file.rs
//         文件、目录操作函数
//
//         created by 关中麦客 1036038462@qq.com

use std::path::Path;
use std::time::UNIX_EPOCH;

/// 组装m3u8文件输出路径
///   入参：视频编码，例如 "2"
///   返回：例如 D:\TMP\root_path\2\video.m3u8
pub fn outfile(code: &str) -> String
{
    let mut path = super::conf::out_path().to_string(); 
    if !path.ends_with("/") && !path.ends_with("\\")
    {
        path.push_str("/");
    }
    path.push_str(code);
    path.push_str("/video.m3u8");

    if cfg!(target_os = "windows")
    {
        return path.replace("/", "\\");
    }
    else
    {
        return path.replace("\\", "/");
    }
}

/// 创建任务目录
pub fn create_task_dir(code: &str)
{
    let mut path = super::conf::out_path().to_string(); 
    if !path.ends_with("/") && !path.ends_with("\\")
    {
        path.push_str("/");
    }
    path.push_str(code);

    if cfg!(target_os = "windows")
    {
        path = path.replace("/", "\\");
    }
    else
    {
        path = path.replace("\\", "/");
    }

    if let Err(err) = std::fs::create_dir_all(&path)
    {
        log::warn!("[process] Can't create dir {}, error: {}", &path, err);
    }
}

/// 删除超时任务文件video.m3u8（未超时不删）
///   pathfile: 文件全路径名
///   sec：超时秒数
pub fn del_timeout_file(code: &str, sec: u32)
{
    let mut path = super::conf::out_path().to_string(); 
    if !path.ends_with("/") && !path.ends_with("\\")
    {
        path.push_str("/");
    }
    path.push_str(code);
    path.push_str("/video.m3u8");

    if cfg!(target_os = "windows")
    {
        path = path.replace("/", "\\");
    }
    else
    {
        path = path.replace("\\", "/");
    }

    if let Some(update_time) = file_update_time(&path)
    {
        // log::info!("删除m3u8文件:{}, update_time:{}, sec:{}", path, update_time, sec);
        if super::util::sec_timestamp() - update_time > sec
        {
            // log::info!("删除");
            let _ = std::fs::remove_file(&path);  //删除文件
        }
    }
}

/// pathfile是否文件且已存在
pub fn file_exist(pathfile: &str) -> bool
{
    let path = Path::new(pathfile);
    if path.is_file()
    {
        return true;
    }

    false
}

/// 获得文件最后更新秒时间戳
pub fn file_update_time(pathfile: &str) -> Option<u32>
{
    // log::info!("文件：{}", pathfile);

    if file_exist(pathfile)
    {
        if let Ok(metadata) = std::fs::metadata(pathfile)
        {
            if let Ok(system_time) = metadata.modified()
            {
                let since_the_epoch = system_time
                                    .duration_since(UNIX_EPOCH)
                                    .expect("Time went backwards");
                let timestamp = since_the_epoch.as_secs() as u32
                        + since_the_epoch.subsec_nanos() / 1_000_000_000;
                return Some(timestamp);
            }
        }
    }

    None
}

